<?php

namespace common\queues;

use Yii;
use yii\base\BaseObject;
use common\models\bonus\Bonus;
use common\models\bonus\BonusDay;
use common\models\bonus\BonusDayMember;
use common\models\forms\CreditsLogForm;
use common\models\member\MemberMoneyDay;
use common\models\bonus\BonusDj;
use common\models\bonus\BonusQi;
use common\models\bonus\BonusQiMember;
use common\models\member\Account;

class BonusJob extends BaseObject implements \yii\queue\JobInterface
{
    public $id;

    public function execute($queue)
    {
        $query = Bonus::find()->with(['member'])->where(['status'=>Bonus::STATUS_DEFAULT]);
        if ($this->id) {
            $query->andWhere(['id'=>$this->id]);
        }
        echo date('Y-m-d H:i:s')."开始结算奖金".$this->id.PHP_EOL;
        $model = $query->one();
        if (!$model) {
            if ($this->id) {
                Yii::$app->queue->delay(2)->push(new \common\queues\BonusJob());
            }
            return false;
        }
        $transaction = Yii::$app->db->beginTransaction();
        
        try{
            $update = Bonus::updateAll(['status'=>Bonus::STATUS_ISPAY, 'pay_at'=>time()], ['id'=>$model->id, 'status'=>Bonus::STATUS_DEFAULT]);
            
            if (!$update) {
                throw new \Exception('状态更新失败', 1);
            }
            echo "状态更新成功".PHP_EOL;
            $remark = Bonus::$typeArr[$model->bonus_type];
            echo $remark.PHP_EOL;
            // try{
                // 添加累计奖金
                Account::updateAllCounters(['bonus_amount'=>$model->amount], ['member_id'=>$model->member->id]);
                Yii::$app->services->memberCreditsLog->incrMoney(new CreditsLogForm([
                    'member' => Yii::$app->services->member->get($model->member_id),
                    'num' => $model->amount,
                    'credit_group' => 'bonus',
                    'remark' => $remark,
                ]));
                Bonus::updateAllCounters(['payment'=>$model->amount], ['id'=>$model->id]);
                $model->payment = $model->amount;
            // } catch (\Exception $e) {
            //     echo $e->getMessage().PHP_EOL;
            // }

            // 汇总
            BonusDay::updateDayDate($model);
            BonusDayMember::updateDayDate($model);
            echo "汇总成功".PHP_EOL;
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            if ($this->id) {
                Yii::$app->queue->delay(2)->push(new \common\queues\BonusJob());
            }
            echo $e->getMessage().PHP_EOL;
        }
    }
}